package com.baizhi.realm;

import com.baizhi.dao.AdminDAO;
import com.baizhi.entity.Admin;
import com.baizhi.service.RolePermissionService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private AdminDAO adminDAO;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名getPrimaryPrincipal()
        String username = principalCollection.getPrimaryPrincipal().toString();
        //根据用户名查询授权信息
        Set<String> roles = rolePermissionService.selectRoleByUsername(username);
        Set<String> permissions = rolePermissionService.selectPermissionUsername(username);
        System.out.println("roles="+roles);
        System.out.println("permissions="+permissions);
        //封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    //获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("开始认证");
        //获取用户名
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //查询数据库
        Admin admin = adminDAO.selectByName(username);
        System.out.println("username=="+username);
        if(admin!=null){
            return new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),this.getName());
        }

        return null;
    }
}
